package com.example.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @version: java version 23
 * @Author: 韩学新
 * @description:
 * @date: 2025-05-17 下午6:05
 */
public class JdbcUtils {

    private JdbcUtils() {
    }

    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;

    static {
        /**
         * 1.读取配置文件
         * 2.赋值变量
         * 3.封装连接方法
         */
        try {
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 查询释放资源
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 增删改释放资源
     * @param statement
     * @param connection
     */
    public static void closeConnection(Statement statement, Connection connection){
        closeConnection(null, statement, connection);
    }

}
